<?php

namespace app\shop\controller\product;

use think\Controller;


class Product extends Controller
{
    protected $ProductModel = null;
    protected $BusinessModel = null;
    protected $AttributeModel = null;
    protected $RelationModel = null;
    protected $CollectionModel = null;
    protected $ProductTopModel;

    public function __construct()
    {
        parent::__construct();

        $this->ProductModel = model('product.Product');
        $this->BusinessModel = model('business.Business');
        $this->AttributeModel = model('product.attribute.Attribute');
        $this->RelationModel = model('product.attribute.Relation');
        $this->CollectionModel = model('business.Collection');
        $this->ProductTopModel = model('product.Top');
    }
    //查询商品分类
    public function type()
    {
        if ($this->request->isAjax()) {
            $typeData = model('product.Type')->order('weigh desc')->select();

            $this->success('查询商品分类数据成功', null, $typeData);
        }
    }

    //查询商品数据
    public function index()
    {
        if ($this->request->isAjax()) {

            $page = $this->request->param('page', 1, 'trim');
            $typeid = $this->request->param('typeid', 0, 'trim');
            $flag = $this->request->param('flag', 0, 'trim');
            $orderBy = $this->request->param('orderBy', 'createtime', 'trim');
            $By = $this->request->param('By', 'desc', 'trim');
            $search = $this->request->param('search', '', 'trim');

            $where = [];

            if ($typeid != 0) {
                $where['typeid'] = intval($typeid);
            }

            if ($flag != 0) {
                $where['flag'] = $flag;
            }

            if (!empty($search)) {
                $where['product.name'] = ['LIKE', "%$search%"];
            }

            $list = $this->ProductModel->with(['unit'])->where($where)->order($orderBy, $By)->page($page, 10)->select();

            $count = $this->ProductModel->with(['unit'])->where($where)->count();

            $data = [
                'list' => $list,
                'count' => $count
            ];

            if ($list) {
                $this->success('查询商品数据成功', null, $data);
            } else {
                $this->error('暂无更多商品', null, $data);
            }
        }
    }

    //查询商品
    public function info()
    {
        if ($this->request->isAjax()) {
            $proid = $this->request->param('proid', 0, 'trim');
            $busid = $this->request->param('busid', 0, 'trim');

            $product = $this->ProductModel->find($proid);

            if (!$product) {
                $this->error('商品不存在');
            }

            $business = $this->BusinessModel->find($busid);

            if ($business) {
                $product['cart_count'] = model('product.Cart')->where(['busid' => $busid, 'proid' => $proid])->count();
                $product['collection_status'] = model('business.Collection')->where(['busid' => $busid, 'collectid' => $proid, 'status' => 'product'])->find() ? true : false;
            } else {
                $product['collection_status'] = false;
                $product['cart_count'] = 0;
            }

            // 商品属性
            $propertiesList = $sku = $list = [];

            // 查询商品关联属性
            $attrid = $this->RelationModel->where(['proid' => $proid])->group('attrid')->column('attrid');

            // 根据属性id获取属性数据
            $attrs = $this->AttributeModel->where(['id' => ['IN', $attrid]])->select();

            if ($attrs) {
                foreach ($attrs as $item) {
                    $propertiesList[$item['id']] = [
                        'k_id' => $item['id'], // 属性id
                        'k' => $item['name'], // 属性名
                        'is_multiple' => false, // 是否多选
                        'v' => [] // 属性值
                    ];
                }
            }

            // 获取该商品的所有属性值的数据
            $relationList = $this->RelationModel->where(['proid' => $proid])->select();

            if ($propertiesList && $relationList) {
                foreach ($relationList as $item) {
                    $propertiesList[$item['attrid']]['v'][] = [
                        'id' => $item['id'], // 属性值id
                        'name' => $item['value'], // 属性值名
                        'price' => (float)bcmul($item['price'], 100, 2), // 该属性值的加价 前端显示的是分单位
                        'text_status' => 1, // 是否正常选择
                    ];
                }
            }

            foreach ($propertiesList as $item) {
                $list[] = [
                    's1' => $item['k_id'], // 规格类目id
                    'price' => (float)bcmul($product['price'], 100, 2), // 价格（单位分）
                    'stock_num' => $product['stock'] // 当前 sku 组合对应的库存
                ];
            }

            // sku
            $sku = [
                'tree' => [], // 一个商品可以有多个规格类目，一个规格类目下可以有多个规格值
                'list' => $list, // 所有 sku 的组合列表
                'price' => $product['price'], // 默认价格（单位元）
                'stock_num' => $product['stock'] // 商品总库存
            ];

            $data = [
                'product' => $product,
                'propertiesList' => $propertiesList,
                'sku' => $sku
            ];

            $this->success("查询商品成功", null, $data);
        }
    }

    //点击收藏
    public function collection()
    {
        if ($this->request->isAjax()) {
            $proid = $this->request->param('proid', 0, 'trim');
            $busid = $this->request->param('busid', 0, 'trim');

            $product = $this->ProductModel->find($proid);

            if (!$product) {
                $this->error('商品不存在');
            }

            $business = $this->BusinessModel->find($busid);

            if (!$business) {
                $this->error('用户不存在');
            }


            // 组装条件
            $whereData = [
                'busid' => $busid,
                'collectid' => $proid,
                'status' => 'product'
            ];

            $collection = $this->CollectionModel->where($whereData)->find();

            if ($collection) {
                $result = $collection->delete();

                $msg = '取消收藏';
            } else {
                $result = $this->CollectionModel->validate('common/business/Collection')->save($whereData);

                $msg = '收藏';
            }

            if ($result === false) {
                $this->error($this->CollectionModel->getError());
            } else {
                $this->success("{$msg}成功");
            }
        }
    }

    //收藏列表
    public function collect()
    {
        if ($this->request->isAjax()) {
            $busid = $this->request->param('busid', 0, 'trim');

            $business = $this->BusinessModel->find($busid);

            if (!$business) {
                $this->error('用户不存在');
            }

            $collection = $this->CollectionModel->with(['collect'])->where(['busid' => $busid])->select();
            $count = $this->CollectionModel->where(['busid' => $busid])->count();

            $data = [
                'list' => $collection,
                'count' => $count
            ];

            if ($collection) {
                $this->success("查找收藏成功", null, $data);
            } else {
                $this->error("查找失败");
            }
        }
    }

    public function slider()
    {
        if ($this->request->isAjax()) {
            $typeid = $this->request->param('typeid', 0, 'trim');
            $page = $this->request->param('page', 1, 'trim');

            $list = $this->ProductModel->where(['typeid' => $typeid])->order('id desc')->page($page, 10)->select();
            $count = $this->ProductModel->where(['typeid' => $typeid])->count();

            $data = [
                'list' => $list,
                'count' => $count
            ];
            if ($list) {
                $this->success("查询分类成功", null, $data);
            } else {
                $this->error('查询失败');
            }
        }
    }

    //商品排行榜
    public function top(){
        if ($this->request->isAjax()) {

            $top = $this->ProductTopModel->select();
            $count = $this->ProductTopModel->count();

            $list = [];
            if ($top) {
                foreach ($top as $item) {
                    $product = $this->ProductModel->where(['id' => $item['proid']])->select();

                    if ($product) {
                        $list[] = $product;
                    }
                }

                if (count($list) == $count) {
                    $data = [
                        'list' => $list,
                        'count' => $count
                    ];
                   $this->success("查找成功",null,$data);
                }
            }else{
                $this->error("查找失败");
            }
        }
    }
}
